package com.ruoyi.system.service.impl;

import java.util.List;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.dto.ProgressDto;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.CustomersMapper;
import com.ruoyi.system.domain.Customers;
import com.ruoyi.system.service.ICustomersService;

import javax.validation.Validator;

/**
 * 客户管理Service业务层处理
 * 
 * @author zzbird
 * @date 2023-11-14
 */
@Service
public class CustomersServiceImpl implements ICustomersService 
{
    private static final Logger log = LoggerFactory.getLogger(CustomersServiceImpl.class);

    @Autowired
    private CustomersMapper customersMapper;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    protected Validator validator;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 查询客户管理
     * 
     * @param customerId 客户管理主键
     * @return 客户管理
     */
    @Override
    public Customers selectCustomersByCustomerId(Long customerId)
    {
        return customersMapper.selectCustomersByCustomerId(customerId);
    }

    /**
     * 查询客户管理列表
     * 
     * @param customers 客户管理
     * @return 客户管理
     */
    @Override
    @DataScope(deptAlias = "x",userAlias = "x")
    public List<Customers> selectCustomersList(Customers customers)
    {
        return customersMapper.selectCustomersList(customers);
    }

    /**
     * 新增客户管理
     *
     * @param customers 客户管理
     * @return 结果
     */
    @Override
    public Customers insertCustomers(Customers customers)
    {
        customers.setCreateTime(DateUtils.getNowDate());
        Long affectedRows = customersMapper.insertCustomers(customers);
        Long generatedKey = customers.getCustomerId();
        return customers;
    }

    /**
     * 修改客户管理
     * 
     * @param customers 客户管理
     * @return 结果
     */
    @Override
    public int updateCustomers(Customers customers)
    {
        customers.setUpdateTime(DateUtils.getNowDate());
        return customersMapper.updateCustomers(customers);
    }

    /**
     * 批量删除客户管理
     * 
     * @param customerIds 需要删除的客户管理主键
     * @return 结果
     */
    @Override
    public int deleteCustomersByCustomerIds(Long[] customerIds)
    {
        return customersMapper.deleteCustomersByCustomerIds(customerIds);
    }

    /**
     * 删除客户管理信息
     * 
     * @param customerId 客户管理主键
     * @return 结果
     */
    @Override
    public int deleteCustomersByCustomerId(Long customerId)
    {
        return customersMapper.deleteCustomersByCustomerId(customerId);
    }

    @Override
    public void updatePlatformProgress(ProgressDto customerProgress) {
        customersMapper.updatePlatformProgress(customerProgress);
    }

    @Override
    public void updateFakePlatformProgress(ProgressDto customerProgress) {
        customersMapper.updateFakePlatformProgress(customerProgress);
    }

    @Override
    public void insertPlatformProgress(ProgressDto customerProgress) {
        customersMapper.insertPlatformProgress(customerProgress);
    }

    @Override
    public List<Customers> getCustomerPlatformsAndProgress(ProgressDto customerProgress) {
        return customersMapper.getCustomerPlatformsAndProgress(customerProgress);
    }

    @Override
    public String importCustomer(List<Customers> userList, Boolean isUpdateSupport, String operName,Long deptId,Long userId) {
        {
            if (StringUtils.isNull(userList) || userList.size() == 0)
            {
                throw new ServiceException("导入客户数据不能为空！");
            }
            int successNum = 0;
            int failureNum = 0;
            StringBuilder successMsg = new StringBuilder();
            StringBuilder failureMsg = new StringBuilder();
            for (Customers user : userList)
            {
                try
                {
                    // 验证是否存在这个用户
                    Customers u = customersMapper.selectCustomersByPhoneNum(user.getPhoneNumber());
                    if (StringUtils.isNull(u))
                    {
                        BeanValidators.validateWithException(validator, user);
                        user.setCreateBy(operName);
                        user.setUserId(userId);
                        user.setDeptId(deptId);
                        customersMapper.insertCustomers(user);
                        successNum++;
                        successMsg.append("<br/>" + successNum + "、客户 " + user.getCustomerName() + " 导入成功");
                    }
                    else if (isUpdateSupport)
                    {
                        BeanValidators.validateWithException(validator, user);
                        user.setCustomerId(u.getCustomerId());
                        user.setUpdateBy(operName);
                        user.setUserId(userId);
                        user.setDeptId(deptId);
                        customersMapper.updateCustomers(user);
                        successNum++;
                        successMsg.append("<br/>" + successNum + "、客户 " + user.getCustomerName() +" - " + user.getPhoneNumber() + " 更新成功");
                    }
                    else
                    {
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、客户 " + user.getCustomerName() +" - " + user.getPhoneNumber() + " 已存在");
                    }
                }
                catch (Exception e)
                {
                    failureNum++;
                    String msg = "<br/>" + failureNum + "、客户 " + user.getCustomerName() + " 导入失败：";
                    failureMsg.append(msg + e.getMessage());
                    log.error(msg, e);
                }
            }
            if (failureNum > 0)
            {
                failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
                throw new ServiceException(failureMsg.toString());
            }
            else
            {
                successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
            }
            return successMsg.toString();
        }
    }
}
